import type { FormInstance } from 'element-plus'
import { ref, nextTick, unref } from 'vue'

import type { ElFormInstance } from '../type'

export const useFormMethods = () => {
  const fromInstance = ref<ElFormInstance>()

  const initializeInstance = (formEl: FormInstance | undefined) => {
    fromInstance.value = formEl
  }

  const getFormInstance = async () => {
    const instance = unref(fromInstance.value)
    await nextTick()
    return instance
  }

  const validate = async () => {
    const instance = await getFormInstance()
    return await instance?.validate()
  }

  const resetForm = async () => {
    const instance = await getFormInstance()
    instance?.resetFields()
  }

  const clearValidate = async () => {
    const instance = await getFormInstance()
    instance?.clearValidate()
  }

  return {
    getFormInstance,
    validate,
    resetForm,
    clearValidate,
    initializeInstance,
    fromInstance
  }
}
